package com.zhanglu.authentication.router;

import com.zhanglu.authentication.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.*;

import com.zhanglu.authentication.bean.request.TokenRequest;
import com.zhanglu.authentication.service.UserService;

import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhanglu
 * @description
 * @date 2017/8/28 20:14
 */
@RestController
@Slf4j
public class TokenRouter {
    @Autowired
    private TokenService tokenService;

    @ApiOperation(value = "注册token,即登录方法", notes = "注册token，返回token，如果返回null，说明token不存在或者用户不存在")
    @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = String.class) })
    @PutMapping("/secure/token")
    public ResponseEntity registerToken(@RequestBody TokenRequest tokenRequest) {
        log.info("registerToken params:[username is {} | password is {}]", tokenRequest.getUsername(), tokenRequest.getPassword());
        return tokenService.registerToken(tokenRequest.getUsername(), tokenRequest.getPassword());
    }

    @ApiOperation(value = "更新token", notes = "用于刷新token，因为本地token时间和db中token时间是有误差的，本地到期之后查询db中，如果没到期就重新生成token返回。返回null说明token不存在或者已经过期")
    @ApiResponses({ @ApiResponse(code = 200, message = "请求成功", response = String.class) })
    @PostMapping("/secure/token")
    //@Secured("ROLE_NORMAL")
    public ResponseEntity refreshToken(@RequestBody String token) {
        log.info("refreshToken params:[token is {}]", token);
        return tokenService.refreshToken(token);
    }
}
